package org.fengling.readingplatform.user.service.Impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import org.fengling.readingplatform.model.dto.user.UserLoginDto;
import org.fengling.readingplatform.model.dto.user.UserRegisterDto;
import org.fengling.readingplatform.model.entity.user.UserInfo;
import org.fengling.readingplatform.model.vo.common.ResultCodeEnum;
import org.fengling.readingplatform.model.vo.user.UserInfoVo;
import org.fengling.readingplatform.common.exception.FenglingException;
import org.fengling.readingplatform.user.mapper.UserInfoMapper;
import org.fengling.readingplatform.user.service.UserInfoService;
import org.fengling.readingplatform.utils.AuthContextUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        // 1.userRegisterDto获取数据
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickname = userRegisterDto.getNickname();

        // 2. 校验参数
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(nickname)) {
            throw new FenglingException(ResultCodeEnum.DATA_ERROR);
        }

        // 3. 校验用户名不能重复
        UserInfo userInfo = userInfoMapper.selectByUsername(username);
        if (userInfo != null) {
            throw new FenglingException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        // 4. 保存用户信息
        userInfo = new UserInfo();
        userInfo.setUserName(username);
        userInfo.setPassword(password);
        userInfo.setNickName(nickname);
        userInfo.setStatus(1);
        userInfo.setLevel("Lv1");
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfoMapper.save(userInfo);
    }

    // 用户登录的方法
    @Override
    public String login(UserLoginDto userLoginDto) {
        // 1. UserLoginDto中获取用户名和密码
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();
        // 2. 根据用户名查询数据库，得到用户信息
        UserInfo userInfo = userInfoMapper.selectByUsername(username);
        if(userInfo == null){
            throw new FenglingException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 3. 比较密码是否一致
        String database_password = userInfo.getPassword();
        if (!database_password.equals(password)) {
            throw new FenglingException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 4. 校验用户是否禁用
        if (userInfo.getStatus() == 0) {
            throw new FenglingException(ResultCodeEnum.ACCOUNT_STOP);
        }

        // 5. 生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        // 6. 把用户信息放到redis中
        redisTemplate.opsForValue().set("user:readingplatform:" + token,
                JSON.toJSONString(userInfo),
                30, TimeUnit.DAYS);

        System.out.println(token);
        System.out.println("登录成功");
        // 7. 返回token
        return token;
    }

    // 获取当前用户信息的方法
    @Override
    public UserInfoVo getCurrentUserInfo(String token) {

        // 从threadLocal中获取用户信息
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        // 将userInfo转换成userInfoVo对象
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }

    // 用户退出的方法
    @Override
    public void logout(String token) {
        redisTemplate.delete("user:readingplatform:" + token);
    }

    // 用户修改的方法
    @Override
    public UserInfoVo update(UserInfo userInfo) {
        // 更新用户信息
        userInfoMapper.update(userInfo);
        // 根据用户名查询用户信息
        String username = userInfo.getUserName();
        // 将userInfo转换成userInfoVo对象
        userInfo = userInfoMapper.selectByUsername(username);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }
}